package com.cyurs.netty.hearteat;

import com.sun.corba.se.impl.orbutil.concurrent.Sync;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/23
 */
public class MyServer {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入Netty提供的IdleStateHandler
                            /**
                             * IdleStateHandler -> 由netty提供的空闲状态处理器
                             * readerIdleTime：表示多长时间没有读，就会发送一个心跳检测包检测是否链接
                             * writerIdleTime：表示多长时间没有写，就会发送一个心跳检测包检测是否链接
                             * allIdleTime：表示多长时间没有读写，就会发送一个心跳检测报检测是否链接
                             *
                             * 当IdleStateEvent 触发后，会传递给管道的下一个handler去处理
                             * 通过调用（触发）下一个handler的userEventTriggered 在该方法中去处理
                             */
                            pipeline.addLast(new IdleStateHandler(8, 5, 2, TimeUnit.SECONDS));

                            pipeline.addLast(new MyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
